package com.oa.common.tree;


import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cuichao
 */
public class TreeUtils {

    private static final Object NULL_ROOT = null;

    private static final TreeUtils utils = new TreeUtils();

    private TreeUtils() {
    }

    public static <T extends TreeNode<T>> List<T> buildTree(List<T> nodes, Object rootKey) {
        List<T> roots = new ArrayList<>();

        for (T node : nodes) {
            if (rootKey == NULL_ROOT) {
                if (node.getParentKey() == NULL_ROOT) {
                    utils.recursionTreeNode(nodes, node);
                    roots.add(node);
                }
            } else if (rootKey.equals(node.getParentKey())) {
                utils.recursionTreeNode(nodes, node);
                roots.add(node);
            }
        }
        return roots;
    }

    private <T extends TreeNode<T>> void recursionTreeNode(List<T> nodes, T parent) {
        for (T node : nodes) {
            if (parent.getChildren() == null) {
                parent.setChildren(new ArrayList<>());
            }
            if (parent.getKey().equals(node.getParentKey())) {
                node.setParent(parent);
                parent.getChildren().add(node);
                recursionTreeNode(nodes, node);
                if (CollectionUtils.isEmpty(node.getChildren())) {
                    return;
                }
            }
        }
    }
}
